/*
 * TOP SECRET Copyright 2006-2015 Transsion.com All right reserved. This software is the confidential and proprietary
 * information of Transsion.com ("Confidential Information"). You shall not disclose such Confidential Information and
 * shall use it only in accordance with the terms of the license agreement you entered into with Transsion.com.
 */
package com.yunji.framework_template.biz.crawler;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.yunji.framework_template.common.util.StringUtil;

/**
 * ClassName:DefaultTitleHandler <br/>
 * Date: 2018年12月17日 下午2:42:55 <br/>
 * 
 * @author fenglibin1982@163.com
 * @Blog http://blog.csdn.net/fenglibing
 * @version
 * @see
 */
public class DefaultTitleHandler extends TitleHandler {

    @Override
    public String getTitle(Element element) {
        String title = element.ownText();
        // 检查链接中是否包含图片
        Element imgElement = element.select("img").first();
        /*
        if (StringUtil.isEmpty(title)) {
            Element spanElement = element.select("span").first();
            if (spanElement != null) {
                title = spanElement.ownText();
            }
        }
        */
        if (StringUtil.isEmpty(title)) {
            // 取a标签的title属性
            title = element.attr("title");
        }
        if (StringUtil.isEmpty(title) && imgElement != null) {
            // 取img标签的title属性
            title = imgElement.attr("title");
            if (StringUtil.isEmpty(title)) {
                // 取img标签的alt属性
                title = imgElement.attr("alt");
                if(title!=null && title.length()<20) {
                    title = null;
                }
            }
        }
        if (StringUtil.isEmpty(title)) {
            title = getOkTile(element);
        }
        if (StringUtil.isEmpty(title)) {
            // 取掉所有的html标签，剩下的肯定是title
            title = StringUtil.removeHtmlTags(element.toString());
        }
        if (!StringUtil.isEmpty(title)) {
            title = StringUtil.replaceSpecialStr(title.trim());
            title = title.trim();
        }
        return title;
    }

    /**
     * 在有些场景中，A标签中有多个HTML标签包含了文字，如包括了发布的日期，来源作者、描述等信息， 如这个链接中的链接：http://dailypost.ng/metro/，这个时候在获取标题的时候就需要判断一下。
     * 目前实现的这个逻辑，是从其多个HTML标签的文字中，如果有文字块的长度超过100的，则提取倒数年第二长的文字块作为标题， 因为此时最长的那块可能是文章描述，否则就取最长的文字块做为标题。
     * 
     * @param element
     * @return
     */
    private String getOkTile(Element element) {
        String title = null;
        final Map<Integer, String> sortedTitleMap = new TreeMap<Integer, String>(new Comparator<Integer>() {

            @Override
            public int compare(Integer o1, Integer o2) {
                if (o1 < 02) {
                    return -1;
                } else if (o1 > 02) {
                    return 1;
                } else {
                    return 0;
                }
            }

        });
        List<String> titleList = getTitleFromImageElement(element);
        if (titleList != null && titleList.size() > 0) {
            titleList.forEach(t -> {
                sortedTitleMap.put(t.length(), t);
            });
        }
        String title1 = null;
        String title2 = null;
        int index = 0;
        for (Map.Entry<Integer, String> entry : sortedTitleMap.entrySet()) {
            if (index % 2 == 0) {
                title1 = entry.getValue();
            } else {
                title2 = entry.getValue();
            }
            index++;
        }
        if (StringUtil.isEmpty(title1) && StringUtil.isEmpty(title2)) {
            title = null;
        } else if (!StringUtil.isEmpty(title1) && StringUtil.isEmpty(title2)) {
            title = title1;
        } else if (StringUtil.isEmpty(title1) && !StringUtil.isEmpty(title2)) {
            title = title2;
        } else if (!StringUtil.isEmpty(title1) && !StringUtil.isEmpty(title2)) {
            if (title1.length() < title2.length() && title2.length() > 100) {
                title = title1;
            } else if (title1.length() > title2.length() && title1.length() > 100) {
                title = title2;
            } else if (title1.length() > title2.length()) {
                title = title1;
            } else if (title1.length() < title2.length()) {
                title = title2;
            }
        }
        return title;
    }

    /**
     * 将A标签中所有的文字块提取出来，放到List中返回
     * @param element
     * @return
     */
    private List<String> getTitleFromImageElement(Element element) {
        List<String> titleList = new ArrayList<String>();
        getTitleFromImageElement(titleList, element);
        return titleList;
    }
    /**
     * 递归获取标签中所有的文字内容，并放到List中
     * @param titleList
     * @param element
     */
    private void getTitleFromImageElement(final List<String> titleList, Element element) {
        Elements children = element.children();
        String text = element.ownText();
        if (!StringUtil.isEmpty(text)) {
            titleList.add(text.trim());
        }
        if (children != null && children.size() > 0) {
            children.forEach(e -> {
                getTitleFromImageElement(titleList, e);
            });
        }
    }
}
